<?php
/**
 * Created by PhpStorm.
 * User: This
 * Date: 2018/11/26
 * Time: 21:15
 */
namespace app\admin\controller;
use app\admin\model\Products;
use think\Db;

class Product extends Base{

    public function _initialize(){
        $this->isLogin();
    }

    /**
     * 产品列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index(){
        $condition = array();
        if($_GET){
            $data = $_GET;
            if($data['time']){
                $time = explode('~',$data['time']);
                $time_str = strtotime(trim($time[0])).','.strtotime(trim($time[1]));
                $condition['product_time'] = array('between',$time_str);
            }
            if($data['keywords']){
                if ($data['type']){
                    switch ($data['type']){
                        case 1 :
                            $condition['product_name'] = array('like','%'.$data['keywords'].'%');
                            break;
                        case 2:
                            $condition['product_id'] = (int)$data['keywords'];
                            break;
                    }
                }else{
                    $condition['product_name'] = array('like','%'.$data['keywords'].'%');
                }
            }

        }
        $product = new Products;
        $info = $product->getPage($condition,'bb_product.product_id,bb_product.product_name,bb_product.product_img,bb_product_category.cate_name,bb_product.product_time,bb_product.product_status');
        foreach ($info as &$v){
            $v['product_time'] = date("Y-m-d H:i:s",$v['product_time']);
            if(!$v['product_img']){
                $v['product_img'] = 'http://'.$_SERVER['HTTP_HOST'].'/baibu/public/static/image/default/nopic.png';
            }
        }

        $page = $info->render();
        $this->assign('page',$page);
        $this->assign('site_title','产品列表-管理后台-百步园艺');
        $this->assign('product',$info);
        return $this->fetch('index');
    }

    /**
     * @throws \think\exception\PDOException
     */
    public function del(){
        if(!$_GET){
            ajaxReturn(0,'参数错误!',-1);
        }
        if(gettype($_GET['product_id']) == 'array'){
            $condition['product_id'] = array('in',$_GET['product_id']);
        }else{
            $condition['product_id'] = $_GET['product_id'];
        }
        //开启事务
        $product = new Products;
        $product->startTrans();
        try{
            $info = $product->getList($condition,'product_img,product_desc');
            foreach ($info as $k => $v){
                if ($v['product_img']){
                    del_file(substr(ROOT_PATH,0,-7).$v['product_img']);
                }
                preg_match_all('/<img.*?src="(.*?)".*?\/?>/i',$v['product_desc'],$img);
                if($img[1]){
                    foreach ($img[1] as $key=>$value){
                        del_file(substr(ROOT_PATH,0,-7).$value);
                    }
                }
            }
            $product->del($condition);
            $product->commit();
            ajaxReturn($_GET['product_id'],'删除成功!',1);
        }catch (\Exception $e){
            $product->rollback();
            ajaxReturn(0,'删除失败!',0);
        }
    }

    /**
     * 发布产品
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add(){
        $product = new Products;
        $cate = $product->getCate('','cate_id,cate_name,cate_pid');
        if($cate){
            foreach ($cate as &$v){
                $v = $v->toArray();
            }
        }
        $new_cate = getTree($cate,0);
        if(request()->isPost()){
            $data = input('post.');
            if(!isset($data['product_name']) || !$data['product_name']){
                ajaxReturn(0,'名称不能为空!',0);
            }
            if(!isset($data['product_cate_id']) || !$data['product_cate_id']){
                ajaxReturn(0,'分类不能为空!',0);
            }
            if(!isset($data['product_desc']) || $data['product_desc'] =='<p><br></p>'){
                ajaxReturn(0,'描述不能为空!',0);
            }
            if(isset($data['article_id']) && !$data['article_id']){
                unset($data['article_id']);
            }

            //正则匹配图片
            $preg = '/<img.*?src="(.*?)".*?\/?>/i';
            $img = array();
            preg_match_all($preg,$data['product_desc'],$img);
            //存在图片
            if($img){
                $path = 'public/uploads/product/'.date('Ymd',time());
                //将img标签替换成+rep+ 以便替换
                $data['product_desc'] = $content = preg_replace($preg,'+rep+', $data['product_desc']);
                foreach ($img[1] as $k => $v){
                    //转义base64文件并保存
                    $src = '/baibu/'.$path.'/'.base64_image_content($v,ROOT_PATH.$path,makeSalt(8));
                    $data['product_desc'] = get_img_thumb_url($data['product_desc'],$src);
                }
            }

            //商品主图
            if($_FILES['image']['name']){
                $files = request()->file('image');
                $image_info = $files->getInfo();
                $file_ext = strrchr($image_info['name'],'.');
                $type = array('.jpg','.png','.gif','jpeg','.JPG','.PNG','.GIF','.JPEG');
                if(in_array($file_ext,$type)){
                    $path = 'public/static/image/product/';
                    $result = $files->move(ROOT_PATH.$path);
                    if($result){
                        $data['product_img'] = '/baibu/'.$path.$result->getSaveName();
                    }else{
                        ajaxReturn(0,'图片保存失败!',0);
                    }
                }else{
                    ajaxReturn(0,'请上传jpg、png、gif、jpeg格式的图片',0);
                }
            }
            $data['product_time'] = time();
            $result = $product->add($data);
            if($result){
                ajaxReturn('/baibu/admin/Product','发布成功!',1);
            }else{
                ajaxReturn(0,'添加失败!',0);
            }
        }

        $this->assign('cate',json_encode($new_cate));
        $this->assign('site_title',"发布产品-管理后台-百步园艺");
        $this->assign('nav','发布产品');
        $this->assign('url','/baibu/admin/Product/add');
        return $this->fetch('add');
    }

    /**
     * 修改产品
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit(){
        $product_id = input('product_id');
        if(!$product_id){
            ajaxReturn(0,'参数错误!',0);
        }
        $product = new Products;
        $info = $product->getOne(array('product_id'=>$product_id),'product_id,product_name,product_remark,product_desc,product_img,product_cate_id,product_status');
        $cate = $product->getCate('','cate_id,cate_name,cate_pid');
        if($cate){
            foreach ($cate as &$v){
                $v = $v->toArray();
            }
        }
        $new_cate = getTree($cate,0);

        if(request()->isPost()){
            $data = input('post.');
            if(!isset($data['product_name']) || !$data['product_name']){
                ajaxReturn(0,'名称不能为空!',0);
            }
            if(!isset($data['product_cate_id']) || !$data['product_cate_id']){
                ajaxReturn(0,'分类不能为空!',0);
            }
            if(!isset($data['product_desc']) || $data['product_desc'] =='<p><br></p>'){
                ajaxReturn(0,'描述不能为空!',0);
            }
            //正则匹配图片
            $preg = '/<img.*?src="(.*?)".*?\/?>/i';
            $img = array();
            $del_img = array();
            preg_match_all($preg,$data['product_desc'],$img);
            preg_match_all($preg,$info['product_desc'],$y_img);

            //存在图片
            if($img[1]){
                $path = 'public/uploads/product/'.date('Ymd',time());
                //将img标签替换成+rep+ 以便替换
                $data['product_desc'] = $content = preg_replace($preg,'+rep+', $data['product_desc']);
                $i = 0;
                foreach ($img[1] as $k => $v){
                    //转义base64文件并保存
                    preg_match('/^(data:\s*image\/(\w+);base64,)/',$v, $result);
                    if($result){
                        $src = '/baibu/'.$path.'/'.base64_image_content($v,ROOT_PATH.$path,makeSalt(8));
                        if(isset($y_img[1][$i])){
                            $del_img[] = $y_img[1][$i];
                        }
                    }else{
                        $src = $y_img[1][$i];
                    }
                    $i ++;
                    $data['product_desc'] = get_img_thumb_url($data['product_desc'],$src);
                }
            }else{
                foreach ($y_img[1] as $k=>$v){
                    $del_img[] = $v;
                }
            }

            //商品主图
            if($_FILES['image']['name']){
                $files = request()->file('image');
                $image_info = $files->getInfo();
                $file_ext = strrchr($image_info['name'],'.');
                $type = array('.jpg','.png','.gif','jpeg','.JPG','.PNG','.GIF','.JPEG');
                if(in_array($file_ext,$type)){
                    $path = 'public/static/image/product/';
                    $result = $files->move(ROOT_PATH.$path);
                    if($result){
                        $data['product_img'] = '/baibu/'.$path.$result->getSaveName();
                        del_file(substr(ROOT_PATH,0,-7).$info['product_img']);
                    }else{
                        ajaxReturn(0,'图片保存失败!',0);
                    }
                }else{
                    ajaxReturn(0,'请上传jpg、png、gif、jpeg格式的图片',0);
                }
            }
//            print_r($del_img);exit;
            $result = $product->edit(array('product_id'=>$data['product_id']),$data);
            if($result){

                if($del_img){
                    foreach ($del_img as $item){
                        del_file(substr(ROOT_PATH,0,-7).$item);
                    }
                }
                ajaxReturn('/baibu/admin/Product/','修改成功!',1);
            }else{
                ajaxReturn(0,'修改失败!',0);
            }
        }

        $this->assign('info',$info);
        $this->assign('cate',json_encode($new_cate));
        $this->assign('site_title',"修改产品-管理后台-百步园艺");
        $this->assign('nav','修改产品');
        $this->assign('url','/baibu/admin/Product/edit');
        return $this->fetch('add');
    }

    /**
     * 修改状态
     */
    public function status(){
        if(!$_GET){
            ajaxReturn(0,'参数错误!',-1);
        }
        $update['product_status'] = $_GET['product_status'];
        $condition['product_id'] = $_GET['product_id'];
        $article = new Products;
        $result = $article->edit($condition,$update);
        if($result){
            switch ($update['product_status']){
                case 1:
                    $data['img'] = '/baibu/public/static/image/default/dui.png';
                    $data['name'] = "product_id={$condition['product_id']}&product_status=0";
                    break;
                default :
                    $data['img'] = '/baibu/public/static/image/default/cuo.png';
                    $data['name'] = "product_id={$condition['product_id']}&product_status=1";
                    break;
            }
            ajaxReturn($data,'操作成功!',1);
        }else{
            ajaxReturn(0,'操作失败!',0);
        }
    }

    /**
     * 分类列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function category(){
        $product = new Products();
        $cate = $product->cagePage('','cate_id,cate_name,cate_pid,cate_remark,cate_status',3);

        $page = $cate->render();

        $this->assign('cate',$cate);
        $this->assign('site_title','');
        $this->assign('page',$page);
        return $this->fetch('category');
    }

    /**
     * 添加分类
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function categoryAdd(){
        $category = new Products;
        $cate = $category->getCate('','cate_id,cate_name,cate_pid');
        if($cate){
            foreach ($cate as &$v){
                $v = $v->toArray();
            }
        }
        $new_cate = getTree($cate,0);
        if(request()->isPost()){
            $data = input('post.');
            if(!isset($data['cate_name']) || !$data['cate_name']){
                ajaxReturn(0,'分类不能为空!',0);
            }
            if(!isset($data['cate_pid'])){
                ajaxReturn(0,'上级分类不能为空!',0);
            }
            if(isset($data['cate_id']) && !$data['cate_id']){
                unset($data['cate_id']);
            }
            $data['cate_time'] = time();
            $result = $category->cateAdd($data);
            if($result){
                ajaxReturn('/baibu/admin/Product/category','添加成功!',1);
            }else{
                ajaxReturn(0,'添加失败!',0);
            }
        }
        $this->assign('cate',json_encode($new_cate));
        $this->assign('site_title','添加产品分类-管理后台-百步园艺');
        $this->assign('nav','添加分类');
        $this->assign('url','/baibu/admin/Product/categoryAdd');
        return $this->fetch('cate_add');
    }

    /**
     * 修改分类
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function categoryEdit(){
        $cate_id = input('cate_id');
        if(!$cate_id){
            ajaxReturn(0,'参数错误!',0);
        }
        $category = new Products;
        $info = $category->cateOne(array('cate_id'=>$cate_id),'cate_id,cate_name,cate_pid,cate_status,cate_remark');
        $cate = $category->getCate('','cate_id,cate_name,cate_pid');
        if($cate){
            foreach ($cate as &$v){
                $v = $v->toArray();
            }
        }
        $new_cate = getTree($cate,0);
        if(request()->isPost()){
            $data = input('post.');
            if(!isset($data['cate_name']) || !$data['cate_name']){
                ajaxReturn(0,'分类不能为空!',0);
            }
            if(!isset($data['cate_pid'])){
                ajaxReturn(0,'上级分类不能为空!',0);
            }

            $result = $category->cateEdit(array('cate_id'=>$cate_id),$data);
            if($result){
                ajaxReturn('/baibu/admin/Product/category','修改成功!',1);
            }else{
                ajaxReturn(0,'修改成功!',0);
            }
        }
        $this->assign('cate',json_encode($new_cate));
        $this->assign('info',$info);
        $this->assign('site_title','修改产品分类-管理后台-百步园艺');
        $this->assign('nav','修改分类');
        $this->assign('url','/baibu/admin/Product/categoryEdit');
        return $this->fetch('cate_add');
    }

    /**
     * 分类删除
     */
    public function categoryDel(){
        if(!$_GET){
            ajaxReturn(0,'参数错误!',-1);
        }
        if(gettype($_GET['cate_id']) == 'array'){
            $condition['cate_id'] = array('in',$_GET['cate_id']);
        }else{
            $condition['cate_id'] = $_GET['cate_id'];
        }
        $product = new Products;
        $result = $product->cateDel($condition);
        if($result){
            ajaxReturn($_GET['cate_id'],'删除成功!',1);
        }else{
            ajaxReturn(0,'删除失败!',0);
        }
    }

    /**
     * 修改状态
     */
    public function categoryStatus(){
        if(!$_GET){
            ajaxReturn(0,'参数错误!',-1);
        }
        $update['cate_status'] = $_GET['cate_status'];
        $condition['cate_id'] = $_GET['cate_id'];
        $product = new Products;
        $result = $product->cateEdit($condition,$update);
        if($result){
            switch ($update['cate_status']){
                case 1:
                    $data['img'] = '/baibu/public/static/image/default/dui.png';
                    $data['name'] = "cate_id={$condition['cate_id']}&cate_status=0";
                    break;
                default :
                    $data['img'] = '/baibu/public/static/image/default/cuo.png';
                    $data['name'] = "cate_id={$condition['cate_id']}&cate_status=1";
                    break;
            }
            ajaxReturn($data,'操作成功!',1);
        }else{
            ajaxReturn(0,'操作失败!',0);
        }
    }

}